import axios from 'axios'
import qs from 'qs'
// import baseUrl from './baseUrl'

// axios.defaults.baseURL = baseUrl
axios.defaults.baseURL = process.env.VUE_APP_BASE_API
axios.defaults.timeout = 20000
// 默认是否允许携带cookie
axios.defaults.withCredentials = true
axios.defaults.headers = {
  'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
}

axios.interceptors.request.use(
  config => {
    // 若是有做鉴权token , 就给头部带上token
    // var token = localStorage.getItem('token')
    // if (token !== null) {
    //   if (token !== '') {
    //     config.headers.token = token
    //   }
    // }
    // store.dispatch('showLoading', '加载中')
    return config
  },
  error => {
    // store.dispatch('hideLoading')
    return Promise.reject(error)
  }
)

axios.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (!error.response) {
      return Promise.reject ({
        message: '请求无响应'
      })
    }
    let message
    switch (error.response.status) {
      case 400:
        message = '错误请求'
        break
      case 401:
        message = '未授权'
        break
      case 403:
        message = '拒绝访问'
        break
      case 404:
        message = '请求路径未找到'
        break
      case 500:
        message = '服务器异常'
        break
      default:
        message = '未知错误'
    }
    return Promise.reject(error)
  }
)

const http = {
  get (url, payload = undefined) {
    return axios({
      method: 'get',
      url:  url,
      params: payload,
      paramsSerializer: params => {
        return qs.stringify(params, { indices: false })
      }
    })
  },
  post (url, payload = undefined) {
    return axios({
      method: 'post',
      url:  url,
      data: payload,
      transformRequest: [
        data => {
          return qs.stringify(data, { indices: false })
        }
      ]
    })
  },
  put (url, payload = undefined) {
    return axios({
      method: 'post',
      url:  url,
      data: payload
    })
  },
  delete (url, payload = undefined) {
    return axios({
      method: 'delete',
      url:  url,
      data: payload
    })
  },
  postJson (url, payload = undefined) {
    return axios({
      method: 'post',
      url:  url,
      data: payload,
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      }
    })
  },
  postFile (url, payload = undefined) {
    return axios({
      method: 'post',
      url:  url,
      data: payload,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  all (promises) {
    return Promise.all(promises)
  },
  getBase () {
    return baseUrl
  }
}

export default http



